package com.atguigu.lease.web.admin.custom.interceptors;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Package: com.atguigu.lease.web.admin.custom.inteceptors
 * @ClassName: LoginProtectHandlerInterceptor
 * @Author luu
 * @create 2024/10/9 20:33
 * @Description:
 */

@Component
public class LoginProtectHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws Exception {
        //1.获取token (约定好，请求头，key是固定: access_token) , 没有直接抛出：
        String accessToken = request.getHeader("access_token");
        if (ObjectUtils.isEmpty(accessToken)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        //2. 检查 token 是否过期和被篡改
        Claims claims = JwtUtil.parseToken(accessToken);
        return true;
    }

}
